<template>
  <div class="login">
    <h1>登录</h1>
    <form @submit.prevent="handleLogin">
      <div>
        <label for="loginName">用户名:</label>
        <input type="text" v-model="loginName" placeholder="请输入用户名" />
      </div>
      <div>
        <label for="password">密码:</label>
        <input type="password" v-model="password" placeholder="请输入密码" />
      </div>
      <button type="submit">登录</button>
    </form>
    <p v-if="errorMessage" class="error">{{ errorMessage }}</p>
  </div>
</template>

<script>
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

export default {
  name: 'LoginForm',
  setup() {
    const router = useRouter()
    const loginName = ref('admin')
    const password = ref('123456')
    const errorMessage = ref('')

    const handleLogin = async () => {
      try {
        console.log(loginName.value, password.value)
        const res = await axios.post('/login', {
          loginName: loginName.value,
          password: password.value,
        })
        if (res.data.ok) {
          alert('登录成功！')
          router.push('/product/add')
        } else {
          errorMessage.value = res.data.message || '登录失败'
        }
      } catch (error) {
        errorMessage.value = '登录失败：' + error.message
      }
    }

    return {
      loginName,
      password,
      errorMessage,
      handleLogin,
    }
  },
}
</script>

<style scoped>
.error {
  color: red;
}
</style>
